import React, { useState, useEffect } from 'react'
import { getProList, deletePro, addPro, updatePro, changePro, selectPro } from '@/api/pro'
import proStyle from '@/styles/pro.module.scss'
import { Table, Space, Button, Popconfirm, Drawer, Form, Input, Modal, Switch, Image, InputNumber, Select, message } from 'antd'
import { useSize } from 'ahooks';

const { Search } = Input; //解构出搜索
const { Option } = Select;

export default function ProList() {
  const [proList, setProList] = useState(); //表格数据
  const [pageSize] = useState(4); //每页显示的商品数量
  const [flag, setFlag] = useState(true); //是否搜索标志
  const [keyword, setKeyword] = useState(''); //搜索关键字
  const [click, setClick] = useState(0); //点击搜索
  const [load, setLoad] = useState(false); //是否加载中
  const [messageApi, contextHolder] = message.useMessage();

  const size = useSize(document.querySelector('body'));

  const successAdd = () => {
    messageApi.open({
      type: 'success',
      content: '添加成功',
    });
  };

  const successUpdate = () => {
    messageApi.open({
      type: 'success',
      content: '修改成功',
    });
  };

  const getProListData = () => { //请求数据函数
    console.log('请求数据了');
    if (!flag) { //如果搜索框没有内容
      getProList().then(res => { //则请求商品列表接口
        setProList(res.data.data);
        console.log(res.data.data);
        setTimeout(() => {
          setLoad(false);
        }, 1000);
      })
    } else { //如果搜索框有内容
      selectPro({ keyword }).then(res => { //则请求搜索商品接口
        setProList(res.data.data);
        setTimeout(() => {
          setLoad(false);
        }, 1000);
      })
    }

  }

  const columns = [ //表格的每一列
    {
      title: '序号',
      // dataIndex: 'pdt_id',
      align: 'center',
      width: 70,
      render(text, record, index) {
        return <span>{index + 1}</span> //显示内容为当页的下标
      }
    },
    {
      title: '商品名',
      dataIndex: 'pdt_name',
      align: 'center'
    },
    {
      title: '数量',
      width: 70,
      dataIndex: 'pdt_num',
      align: 'center'
    },
    {
      title: '类型',
      width: 100,
      dataIndex: 'pdt_type',
      align: 'center'
    },
    {
      title: '状态',
      dataIndex: 'pdt_sale',
      width: 130,
      align: 'center',
      render(text, record) {
        return <Switch
          checkedChildren="在售"
          unCheckedChildren="下架"
          checked={text ? true : false}
          onChange={(cheaked) => { changeSale(record.pdt_id, cheaked); }} //切换在售状态
        />
      }
    },
    {
      title: '描述',
      align: 'center',
      dataIndex: 'pdt_describe',
    },
    {
      title: '预览图',
      dataIndex: 'pdt_preview',
      render(text, record, index) {
        return <Image style={{ width: '80px' }} src={text} alt="图片加载失败" />
      },
      align: 'center'
    },
    {
      title: '价格',
      dataIndex: 'pdt_price',
      render(text, record, index) {
        return text.toFixed(2) + '元';
      },
      sorter: {
        compare: (a, b) => a.pdt_price - b.pdt_price,
      },
      align: 'center'
    },
    {
      title: '操作',
      dataIndex: 'pdt_id',
      align: 'center',
      render(text, record, index) {
        return (<>
          <Space>

            <Button type='primary' onClick={() => {
              showModal(text, record); //显示编辑弹窗
            }}>编辑</Button>

            <Popconfirm
              title="确定删除吗"
              okText="确定"
              cancelText="取消"
              onConfirm={() => {
                // console.log(record.pdt_id);
                deletePro({ id: record.pdt_id }).then(res => { //删除产品
                  // console.log(res);
                  getProListData(); //重新获取数据
                })
              }}
            >
              <Button type='primary' danger >删除</Button>
            </Popconfirm>
          </Space>
        </>)
      }
    }

  ];

  useEffect(() => {
    getProListData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [click]) //监听搜索按钮的点击事件

  const onSelectChange = (newSelectedRowKeys) => { //改变页数函数
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const [selectedRowKeys, setSelectedRowKeys] = useState([]); //分页器状态

  const rowSelection = { //选择器
    selectedRowKeys,
    onChange: onSelectChange
  };

  const [open, setOpen] = useState(false); //添加窗口的打开状态

  const showDrawer = () => { //打开添加窗口函数
    setOpen(true);
  };

  const onClose = () => { //关闭添加窗口函数
    setOpen(false);
  };

  const clearForm = () => { //清空表单函数
    setPdtName('');
    setPdtNum('');
    setPdtType('');
    setPdtPrice('');
    setPdtPreview('');
  }

  const [pdtId, setPdtId] = useState(); //产品id
  const [pdtName, setPdtName] = useState(''); //产品名字
  const [pdtNum, setPdtNum] = useState(''); //产品数量
  const [pdtType, setPdtType] = useState(''); //产品种类
  const [pdtPrice, setPdtPrice] = useState(''); //产品价格
  const [pdtPreview, setPdtPreview] = useState(''); //产品预览图
  const [pdtDescribe, setPdtDescribe] = useState(''); //产品预览图

  const onAdd = () => { //产品添加函数
    const result = { //提交的表单内容
      pdt_name: pdtName,
      pdt_price: pdtPrice,
      pdt_num: +pdtNum,
      pdt_type: pdtType,
      pdt_sale: 0,
      pdt_preview: pdtPreview,
      pdt_describe: pdtDescribe
    }

    addPro(result).then(res => { //产品添加接口
      getProListData(); //重新获取数据
      successAdd(); //成功添加消息提示
      clearForm(); //清空表单
      onClose(); //关闭窗口
    });
  }

  const [isModalOpen, setIsModalOpen] = useState(false); //编辑商品窗口打开状态

  const showModal = (text, record) => { //打开编辑窗口并填充数据函数
    setPdtId(record.pdt_id);
    setPdtName(prevName => record.pdt_name);
    setPdtNum(prevNum => parseInt(record.pdt_num));
    setPdtType(prevType => record.pdt_type);
    setPdtPrice(prevPrice => parseFloat(record.pdt_price));
    setPdtPreview(prevPreview => record.pdt_preview);
    setPdtDescribe(prevDescribe => record.pdt_describe);
    setIsModalOpen(true);
  };



  const handleOk = () => { //提交编辑
    const result = { //编辑商品表单
      pdt_name: pdtName,
      pdt_price: pdtPrice,
      pdt_num: +pdtNum,
      pdt_type: pdtType,
      pdt_sale: 0,
      pdt_preview: pdtPreview,
      pdt_describe: pdtDescribe
    }
    // console.log('这是id', pdtId);
    updatePro({ id: pdtId }, result).then(res => { //更新商品接口
      getProListData(); //重新获取数据
      successUpdate(); //修改成功弹窗
      clearForm(); //清空表单
      setIsModalOpen(false); //关闭编辑窗口
    })
  };

  const handleCancel = () => { //编辑取消函数
    setIsModalOpen(false); //关闭编辑窗口
    clearForm(); //清空表单
  };

  const changeSale = (id, checked) => { //切换在售状态函数
    changePro({ id }, { pdt_sale: +checked }).then(res => { //切换在售状态接口
      getProListData(); //重新获取数据
    })
  }

  const onSearch = (value) => { //搜索商品函数
    setKeyword(value); //设置搜索关键字状态
    setLoad(true);//设置搜索加载状态
    if (value) { //如果搜索框不为空
      setFlag(true); //设置搜索状态为真
    } else { //否则
      setFlag(false); //设置搜索状态为假
    }
    setClick(click + 1); //每次点击搜索按钮触发
  };

  return (
    <Space style={{ width: '100%', position: 'relative' }} direction='vertical'>
      {contextHolder}
      <Drawer title="添加产品" placement="right" onClose={onClose} open={open}>
        <Space direction='vertical'>
          <Form autoComplete="off">
            <Form.Item
              name='pdtName'
              label="商品名"
              rules={[
                {
                  required: true,
                  message: '请输入商品名!',
                },
                {
                  max: 127,
                  message: '输入内容过长'
                }
              ]}
            >
              <Input value={pdtName} onChange={e => { setPdtName(e.target.value) }}></Input>
            </Form.Item>

            <Form.Item
              name='pdtNum'
              label="商品数量"
              rules={[
                {
                  required: true,
                  message: '请输入商品数量!'
                },
              ]}
            >
              <InputNumber formatter={(value) => value}
                parser={(value) => value.split('.')[0]}
                min={0} max={99999} value={pdtNum}
                onChange={value => { setPdtNum(value); }}></InputNumber>
            </Form.Item>

            <Form.Item
              label="商品类型"
              name='pdtType'
              rules={[
                {
                  required: true,
                },
              ]}
            >
              <Select
                placeholder="选择商品类型"
                onChange={value => { setPdtType(value) }}
                allowClear
                value={pdtType}
              >
                <Option value="保健">保健</Option>
                <Option value="化妆">化妆</Option>
                <Option value="娱乐">娱乐</Option>
                <Option value="家具">家具</Option>
                <Option value="手机">手机</Option>
                <Option value="日化">日化</Option>
                <Option value="智能">智能</Option>
                <Option value="服装">服装</Option>
                <Option value="特产">特产</Option>
                <Option value="运动">运动</Option>
                <Option value="鞋包">鞋包</Option>
                <Option value="食品">食品</Option>
                <Option value="饰品">饰品</Option>
                <Option value="运动">运动</Option>
              </Select>
            </Form.Item>

            <Form.Item
              label="商品价格"
              name='pdtPrice'
              rules={[
                {
                  required: true,
                  message: '请输入商品价格!',
                },
              ]}
            >
              <InputNumber
                min={0} max={99999999} value={pdtPrice}
                formatter={(value) => `$ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                parser={(value) => {
                  value += '';
                  const val = value.split('.')
                  if (val[1])
                    value = `${val[0]}.${val[1].slice(0, 2)}`;
                  return value.replace(/\$\s?|(,*)/g, '');
                }}
                onChange={value => { setPdtPrice(value); console.log(value); }}></InputNumber>
            </Form.Item>

            <Form.Item
              name='pdtPreview'
              label="商品预览图"
              rules={[
                {
                  required: true,
                  message: '请输入商品预览图链接!',
                },
                {
                  type: 'url',
                  message: '请输入正确的链接格式'
                },
                {
                  max: 127,
                  message: '输入内容过长'
                }
              ]}
            >
              <Input value={pdtPreview} onChange={e => { setPdtPreview(e.target.value) }}></Input>
            </Form.Item>
            <Image style={{ width: '80px' }} src={pdtPreview} />

            <Form.Item
              name='pdtDescribe'
              label="商品描述"
              rules={[
                {
                  required: true,
                  message: '请输入商品描述!',
                },
                {
                  max: 127,
                  message: '输入内容过长'
                }
              ]}
            >
              <Input value={pdtDescribe} onChange={e => { setPdtDescribe(e.target.value) }}></Input>
            </Form.Item>

            <Button onClick={() => { onAdd(); }}>添加</Button>
          </Form>
        </Space>
      </Drawer>

      <Modal title="修改商品" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
        <Space direction='vertical'>
          <Form>
            <Form.Item label="商品名">
              <Input value={pdtName} onChange={e => { setPdtName(e.target.value) }}></Input>
            </Form.Item>

            <Form.Item label="商品数量">
              <InputNumber formatter={(value) => value}
                parser={(value) => value.split('.')[0]}
                defaultValue={0} min={0} max={99999} value={pdtNum}
                onChange={value => { setPdtNum(value); }}>
              </InputNumber>
            </Form.Item>

            <Form.Item label="商品类型">
              <Select
                placeholder="选择商品类型"
                onChange={value => { setPdtType(value) }}
                allowClear
                value={pdtType}
              >
                <Option value="保健">保健</Option>
                <Option value="化妆">化妆</Option>
                <Option value="娱乐">娱乐</Option>
                <Option value="家具">家具</Option>
                <Option value="手机">手机</Option>
                <Option value="日化">日化</Option>
                <Option value="智能">智能</Option>
                <Option value="服装">服装</Option>
                <Option value="特产">特产</Option>
                <Option value="运动">运动</Option>
                <Option value="鞋包">鞋包</Option>
                <Option value="食品">食品</Option>
                <Option value="饰品">饰品</Option>
                <Option value="运动">运动</Option>
              </Select>
            </Form.Item>

            <Form.Item label="商品价格">
              <InputNumber
                defaultValue={0} min={0} max={99999999} value={pdtPrice}
                formatter={(value) => `$ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                parser={(value) => {
                  value += '';
                  const val = value.split('.')
                  if (val[1])
                    value = `${val[0]}.${val[1].slice(0, 2)}`;
                  return value.replace(/\$\s?|(,*)/g, '');
                }}
                onChange={value => { setPdtPrice(value); console.log(value); }}>
              </InputNumber>
            </Form.Item>

            <Form.Item label="商品预览图">
              <Input value={pdtPreview} onChange={e => { setPdtPreview(e.target.value); console.log('更改了'); }}></Input>
              <Image style={{ width: '80px' }} src={pdtPreview} />
            </Form.Item>

            <Form.Item label="商品描述">
              <Input value={pdtDescribe} onChange={e => { setPdtDescribe(e.target.value) }}></Input>
            </Form.Item>

            <Button onClick={() => { onAdd(); }}>添加</Button>
          </Form>
        </Space>
      </Modal>

      <Space className={proStyle.btns}>
        <Button onClick={() => { showDrawer() }}>添加产品</Button>
        {
          selectedRowKeys.length > 1 ? //如果选中的商品数量大于1，显示批量删除按钮
            <Popconfirm
              title="确定删除吗"
              okText="确定"
              cancelText="取消"
              onConfirm={() => {
                selectedRowKeys.forEach(id => {  //遍历被选中的商品的id
                  deletePro({ id: id }).then(res => { //依次删除商品
                    getProListData(); //重新获取数据
                  })
                  setSelectedRowKeys([]); //设置被选中的商品的id数组为空
                })
              }}
            >
              <Button
                danger
              >批量删除</Button>
            </Popconfirm> : null
        }
        <Search
          addonBefore="搜索商品"
          placeholder="请输入关键字"
          allowClear
          onSearch={onSearch}
          className={proStyle.search}
          loading={load}
          style={{
            width: 304,
          }}
        />
      </Space>

      <Table
        style={{ width: '100%' }}
        dataSource={proList}
        columns={columns}
        rowKey={record => record.pdt_id}
        scroll={{ y: size.height - 380, x: 1200 }}
        pagination={{ pageSize }}
        rowSelection={rowSelection}
      />
    </Space>
  )
}
